package com.zzyy.study;

import java.util.concurrent.TimeUnit;

class Singleton
{
    private static volatile Singleton instance;

    private Singleton(){
        System.out.println(Thread.currentThread().getName()+"\t"+"单例模式构造方法only出现一次");
    }

    public static Singleton getInstance()
    {
        if (instance == null)
        {
            synchronized (Singleton.class)
            {
                if(instance == null)
                {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }

    @Override
    public String toString()
    {
        return "Singleton{}";
    }
}

/**
 * @auther zzyy
 * @create 2024-03-26 10:45
 *
 * 单例模式
 */
public class T3
{
    public static void main(String[] args)
    {
        /*Singleton singleton;

        for (int i = 0; i < 5; i++) {
            singleton = Singleton.getInstance();
            System.out.println(singleton);
        }*/
        //暂停毫秒
        try { TimeUnit.MILLISECONDS.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); }
        System.out.println("===================");

        for (int i = 1; i <=5; i++) {
            new Thread(() -> {
                Singleton instance = Singleton.getInstance();
                System.out.println(instance+"多线程");
            },String.valueOf(i)).start();
        }
    }
}
